/*
 * Copyright (C) 2010 Fred Barrie This program is free software: you can
 * redistribute it and/or modify it under the terms of the GNU General Public
 * License as published by the Free Software Foundation, either version 3 of the
 * License, or (at your option) any later version. This program is distributed
 * in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even
 * the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
 * See the GNU General Public License for more details. You should have received
 * a copy of the GNU General Public License along with this program. If not, see
 * <http://www.gnu.org/licenses/>.
 */
package org.aergia.vinny.main;

import java.io.File;
import java.util.Calendar;

import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import org.aergia.vinny.database.Database;
import org.aergia.vinny.database.DatabaseImpl;
import org.aergia.vinny.database.pojo.Card;
import org.aergia.vinny.database.pojo.Location;
import org.aergia.vinny.database.pojo.Scan;
import org.aergia.vinny.database.pojo.Workstation;
import org.aergia.vinny.util.DateUtil;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

/**
 * @author Fred
 */
public class ImportMain {

	/**
	 * @param args
	 */
	public static void main(final String[] args) throws Exception {
		String fileName = null;
		if (args.length > 0) {
			fileName = args[0];
		} else {
			fileName = "volunteers.xml";
		}
		new ImportMain().execute(fileName);
	}

	Database database;
	Location location;
	Workstation workstation;

	private void execute(final String fileName) throws Exception {
		final EntityManagerFactory emf = Persistence.createEntityManagerFactory("vinny");
		this.database = new DatabaseImpl(emf.createEntityManager());

		final DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
		final File file = new File(fileName);

		final Document document = builder.parse(file);
		final Element element = document.getDocumentElement();

		if (element.getNodeName().equals("volunteer-list")) {
			this.parseVolunteerList(element, true);
		}

		if (element.getNodeName().equals("volunteer-list")) {
			this.parseVolunteerList(element, false);
		}

	}

	private void parseScan(final Element element, final Card card, final boolean validate) {
		final String scanDate = element.getAttribute("date");
		final Calendar calendar = DateUtil.getInstance(scanDate);

		final Scan scan = new Scan(card, this.workstation, calendar);
		scan.setComment("Imported Scan");
		scan.setLocation(this.location);

		if (!validate) {
			this.database.addScan(scan);
		} else {
			System.out.println("insert into card (id, active, scanTime, card_id, location_id) value (ID,1," + scanDate + "," + card.getId() + ","
					+ this.location.getId() + ")");
		}
	}

	private void parseVolunteer(final Element root, final boolean validate) {
		final String cardNumber = root.getAttribute("card");

		final Card card = this.database.getCard(cardNumber).getResult();
		if (card == null) {
			System.out.println("Card " + cardNumber + " does not exist!");
			System.exit(-1);
		}

		final NodeList list = root.getChildNodes();
		for (int i = 0; i < list.getLength(); i++) {
			final Node node = list.item(i);
			if (node.getNodeType() == Node.ELEMENT_NODE) {
				final Element element = (Element) node;
				if (node.getNodeName().equals("scan")) {
					this.parseScan(element, card, validate);
				}
			}
		}
	}

	private void parseVolunteerList(final Element root, final boolean validate) {
		final String locationId = root.getAttribute("location");
		this.location = this.database.getLocation(Integer.parseInt(locationId)).getResult();

		if (this.location == null) {
			System.out.println("Location does not exist");
			System.exit(-1);
		}

		final NodeList list = root.getChildNodes();

		for (int i = 0; i < list.getLength(); i++) {
			final Node node = list.item(i);
			if (node.getNodeType() == Node.ELEMENT_NODE) {
				final Element element = (Element) node;
				if (element.getNodeName().equals("volunteer")) {
					this.parseVolunteer(element, validate);
				}
			}
		}
	}
}
